package com.payment.ktb.activity.main1;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.widget.base.BottomBaseDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.adapter.AddCreditBankCardAdapter;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.BindCardEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/9/8.
 */

public class OrderConfirmBuyMembershipActivity extends BaseActivity {

    @BindView(R.id.et_orderconfirmbuymembership_bankcardno)
    EditText et_orderconfirmbuymembership_bankcardno;
    @BindView(R.id.tv_orderconfirmbuymembership_amount)
    TextView tv_orderconfirmbuymembership_amount;
    @BindView(R.id.tv_orderconfirmbuymembership_creditcardname)
    TextView tv_orderconfirmbuymembership_creditcardname;
    @BindView(R.id.tv_orderconfirmbuymembership_ordertype)
    TextView tv_orderconfirmbuymembership_ordertype;

    private BaseAnimatorSet mBasIn;
    private List<BindCardEntity> bindCardEntities;
    private AddCreditBankCardAdapter adapter;
    private Context thisActivity;
    BankNameBottomDialog mBankNameBottomDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderconfirmbuymembership);
        ButterKnife.bind(this);
        initTitle("订单确认");
        mBasIn = new BounceTopEnter();
        mBankNameBottomDialog = new BankNameBottomDialog(mContext);
        thisActivity = this;
        et_orderconfirmbuymembership_bankcardno.addTextChangedListener(textWatcher);

        initData();
    }

    private void initData() {

        if (getIntent().getStringExtra("srcActivity").equals("MembershipCenterActivity")) {
            tv_orderconfirmbuymembership_ordertype.setText("购买会员");
        }else if (getIntent().getStringExtra("srcActivity").equals("AgentOrderActivity")) {
            tv_orderconfirmbuymembership_ordertype.setText("后台管理费");
        }else {
            tv_orderconfirmbuymembership_ordertype.setText("未知类型");
        }

        tv_orderconfirmbuymembership_amount.setText("¥ " + handleFen2Yuan(getIntent().getStringExtra("amount")));

        //绑定支付信用卡
        bindCardEntities = new Gson().fromJson(getIntent().getStringExtra("bindCards"), new TypeToken<List<BindCardEntity>>() {}.getType());
        if (bindCardEntities == null || bindCardEntities.isEmpty()) {
            tv_orderconfirmbuymembership_creditcardname.setText("新信用卡");
        }else {
            tv_orderconfirmbuymembership_creditcardname.setText(bindCardEntities.get(0).getCardBank());
            et_orderconfirmbuymembership_bankcardno.setText(bindCardEntities.get(0).getCardNo());
        }


    }


    private String handleFen2Yuan(String fen) {
        if (fen.equals("0")) {
            return "0.00";
        }
        double srcFen = Double.valueOf(fen);
        double roundSrcFen = Math.round(srcFen);
        return String.valueOf(roundSrcFen/100);
    }


    @OnClick({R.id.rl_orderconfirmbuymembership_bankcard,R.id.btn_orderconfirmbuymembership_confirm})
    public void clickEvent(View view) {

        switch (view.getId()) {

            //弹出选择银行卡
            case R.id.rl_orderconfirmbuymembership_bankcard:
                mBankNameBottomDialog.showAnim(mBasIn).show();
                break;


            //支付界面
            case R.id.btn_orderconfirmbuymembership_confirm:

                if (TextUtils.isEmpty(et_orderconfirmbuymembership_bankcardno.getText().toString().trim()) || et_orderconfirmbuymembership_bankcardno.getText().toString().trim().length() < 13 || et_orderconfirmbuymembership_bankcardno.getText().toString().trim().length() > 19) {
                    ToastUtils.showToast("请输入正确的卡号");
                }else {
                    bindOrderAndCard();
                }

                break;

        }



    }




    //绑定信用卡和订单
    private void bindOrderAndCard() {

        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("orderNo",getIntent().getStringExtra("orderNo"));
        map.put("cardNo",et_orderconfirmbuymembership_bankcardno.getText().toString().trim());

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.PayOrderNocardBank, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    Intent intent = null;

                    if (jsonObject.optString("isBind").equals("0")) {
                        intent = new Intent(mContext,OrderConfirmNoBindCardActivity.class);
                    }else {
                        intent = new Intent(mContext,OrderConfirmBindCardActivity.class);
                    }
                    intent.putExtra("amount",getIntent().getStringExtra("amount"));
                    intent.putExtra("cardBank",jsonObject.optString("cardBank"));
                    intent.putExtra("orderNo",jsonObject.optString("orderNo"));
                    intent.putExtra("cardPhone",jsonObject.optString("cardPhone"));
                    intent.putExtra("cardNo",et_orderconfirmbuymembership_bankcardno.getText().toString().trim());
                    startActivity(intent);


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    class BankNameBottomDialog extends BottomBaseDialog<BankNameBottomDialog> {

        ListView lv_orderconfirm_bankcard;
        RelativeLayout rl_orderconfirm_deletebankcard;
        LinearLayout ll_orderconfirm_addnewcard;

        public BankNameBottomDialog(Context context, View animateView) {
            super(context, animateView);
        }

        public BankNameBottomDialog(Context context) {
            super(context);
        }

        @Override
        public View onCreateView() {
            showAnim(new FlipVerticalSwingEnter());
            dismissAnim(null);
            View inflate = View.inflate(mContext, R.layout.dialog_orderconfirm_bankcard, null);
            lv_orderconfirm_bankcard = (ListView) inflate.findViewById(R.id.lv_orderconfirm_bankcard);
            rl_orderconfirm_deletebankcard = (RelativeLayout) inflate.findViewById(R.id.rl_orderconfirm_deletebankcard);
            ll_orderconfirm_addnewcard = (LinearLayout) inflate.findViewById(R.id.ll_orderconfirm_addnewcard);

            //data
            for (int i = 0; i <bindCardEntities.size() ; i++) {
                if (i == 0) {
                    bindCardEntities.get(i).setSelected(true);
                }
            }

//            //adapter
            adapter = new AddCreditBankCardAdapter(thisActivity,bindCardEntities);
//            //bind
            lv_orderconfirm_bankcard.setAdapter(adapter);

            return inflate;
        }

        @Override
        public void setUiBeforShow() {

            rl_orderconfirm_deletebankcard.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mBankNameBottomDialog.dismiss();
                }
            });

            ll_orderconfirm_addnewcard.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mBankNameBottomDialog.dismiss();
                    tv_orderconfirmbuymembership_creditcardname.setText("新信用卡");
                    et_orderconfirmbuymembership_bankcardno.setText("");
                }
            });

            lv_orderconfirm_bankcard.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    for (int j = 0; j < bindCardEntities.size(); j++) {
                        if (j == i){
                            bindCardEntities.get(j).setSelected(true);
                        }else {
                            bindCardEntities.get(j).setSelected(false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    et_orderconfirmbuymembership_bankcardno.setText(bindCardEntities.get(i).getCardNo());
                    mBankNameBottomDialog.dismiss();
                }
            });
        }
    }



    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String etValues = s.toString();
            tv_orderconfirmbuymembership_creditcardname.setText("新信用卡");
            if (bindCardEntities != null && !bindCardEntities.isEmpty()) {
                for (BindCardEntity bindCardEntity:bindCardEntities) {
                    if (bindCardEntity.getCardNo().equals(etValues)) {
                        tv_orderconfirmbuymembership_creditcardname.setText(bindCardEntity.getCardBank());
                        break;
                    }
                }
            }
        }

    };




}
